package apis

import (
	"go-admin/app/admin/models"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/api"
)

type SysSip struct {
	api.Api
}

// Notify 消息通知结构
type NotifyRequset struct {
	Method string      `json:"method"`
	Data   interface{} `json:"data"`
}

func (e SysSip) Notify(c *gin.Context) {
	var req NotifyRequset
	e.MakeContext(c).MakeOrm()
	if err := c.ShouldBindJSON(&req); err != nil {
		e.Error(500, err, "参数绑定失败")
		return
	}
	switch req.Method {
	case "devices.register":
		e.deviceRegister(req.Data)
	case "devices.active":
		e.deviceActive(req.Data)
	case "devices.update":
		e.deviceUpdate(req.Data)
	case "channels.active":
		e.channelActive(req.Data)
	case "devices.location":
		e.deviceLocation(req.Data)
	case "devices.alarm":
		e.deviceAlarm(req.Data)
	}
	c.String(http.StatusOK, "OK")
}

// 设备注册
func (e SysSip) deviceRegister(data any) {
	deviceId := data.(map[string]interface{})["deviceid"].(string)
	// 查询设备
	var device models.SysDevice
	if err := e.Orm.Model(&models.SysDevice{}).Where("device_id = ?", deviceId).First(&device).Error; err != nil {
		// 插入设备
		device = models.SysDevice{
			DeviceId: deviceId,
			Name:     deviceId,
			Status:   2,
			ActiveAt: time.Now(),
		}
		device.CreatedAt = time.Now()
		// 保存设备
		if err := e.Orm.Save(&device).Error; err != nil {
			e.Error(500, err, "设备注册失败")
			return
		}
		return
	}
}

// 设备激活
func (e SysSip) deviceActive(data any) {
	deviceId := data.(map[string]interface{})["deviceid"].(string)
	status := data.(map[string]interface{})["status"].(string)
	timestamp := data.(map[string]interface{})["time"].(float64)
	// 查询设备
	var device models.SysDevice
	if err := e.Orm.Model(&models.SysDevice{}).Where("device_id = ?", deviceId).First(&device).Error; err != nil {
		// 插入设备
		device = models.SysDevice{
			DeviceId: deviceId,
			Name:     deviceId,
			Status:   2,
			ActiveAt: time.Unix(int64(timestamp), 0),
		}
		device.CreatedAt = time.Unix(int64(timestamp), 0)
		// 保存设备
		if err := e.Orm.Save(&device).Error; err != nil {
			e.Error(500, err, "设备激活失败01")
			return
		}
		return
	} else {
		// 更新在线状态和时间
		if status == "ON" || status == "OK" {
			device.Status = 2
		} else {
			device.Status = 1
		}
		activeAt := time.Unix(int64(timestamp), 0)
		device.ActiveAt = activeAt
		// 保存设备
		if err := e.Orm.Save(&device).Error; err != nil {
			e.Error(500, err, "设备激活失败02")
			return
		}
	}

}

// 设备更新
func (e SysSip) deviceUpdate(data any) {
	deviceId := data.(map[string]interface{})["deviceid"].(string)
	// 查找设备
	var device models.SysDevice
	if err := e.Orm.Model(&models.SysDevice{}).Where("device_id = ?", deviceId).First(&device).Error; err != nil {
		e.Error(500, err, "更新设备，设备不存在")
		return
	} else {
		// 更新设备信息
		device.Manufacturer = data.(map[string]interface{})["manufacturer"].(string)
		device.DeviceType = data.(map[string]interface{})["devicetype"].(string)
		device.Firmware = data.(map[string]interface{})["firmware"].(string)
		device.DeviceModel = data.(map[string]interface{})["model"].(string)
		activeAt := time.Now()
		device.ActiveAt = activeAt
		// 保存设备
		if err := e.Orm.Save(&device).Error; err != nil {
			e.Error(500, err, "设备更新失败")
			return
		}
	}
}

// 通道激活
func (e SysSip) channelActive(data any) {
	deviceId := data.(map[string]interface{})["deviceid"].(string)
	channelId := data.(map[string]interface{})["channelid"].(string)
	channelName := data.(map[string]interface{})["name"].(string)
	status := data.(map[string]interface{})["status"].(string)
	timestamp := data.(map[string]interface{})["time"].(float64)
	// 查找通道
	var channel models.SysChannel
	if err := e.Orm.Model(&models.SysChannel{}).Where("device_id = ? AND channel_id = ?", deviceId, channelId).First(&channel).Error; err != nil {
		// 插入通道
		channel = models.SysChannel{
			DeviceId:  deviceId,
			ChannelId: channelId,
			Name:      channelName,
			Status:    2,
			ActiveAt:  time.Unix(int64(timestamp), 0),
		}
		channel.CreatedAt = time.Unix(int64(timestamp), 0)
		// 保存通道
		if err := e.Orm.Save(&channel).Error; err != nil {
			e.Error(500, err, "创建通道失败02")
			return
		}

		return
	} else {
		// 更新通道状态和时间
		if status == "ON" || status == "OK" {
			channel.Status = 2
		} else {
			channel.Status = 1
		}
		activeAt := time.Unix(int64(timestamp), 0)
		channel.ActiveAt = activeAt
		// 保存通道
		if err := e.Orm.Save(&channel).Error; err != nil {
			e.Error(500, err, "通道激活失败")
			return
		}

	}

}

// 设备位置
func (e SysSip) deviceLocation(data any) {
	// 插入位置
	location := models.SysLocation{
		ChannelId: data.(map[string]interface{})["channelid"].(string),
		DeviceId:  data.(map[string]interface{})["deviceid"].(string),
	}
	// 解析位置信息
	location.LocationTime = time.Now()
	// 解析经纬度
	location.Longitude = data.(map[string]interface{})["longitude"].(float64)
	location.Latitude = data.(map[string]interface{})["latitude"].(float64)
	// 解析速度
	location.Speed = data.(map[string]interface{})["speed"].(float64)
	// 解析方向
	location.Direction = data.(map[string]interface{})["direction"].(float64)
	// 解析海拔
	location.Altitude = data.(map[string]interface{})["altitude"].(float64)
	location.CreatedAt = time.Now()
	// 保存位置
	if err := e.Orm.Save(&location).Error; err != nil {
		e.Error(500, err, "位置保存失败")
		return
	}

}

// 设备报警
func (e SysSip) deviceAlarm(data any) {
	// 插入报警
	alarm := models.SysAlarm{
		ChannelId: data.(map[string]interface{})["channelid"].(string),
		DeviceId:  data.(map[string]interface{})["deviceid"].(string),
	}
	// 解析报警信息
	alarm.AlarmTime = time.Now()
	alarm.AlarmPriority = int(data.(map[string]interface{})["alarmPriority"].(float64))
	alarm.AlarmMethod = int(data.(map[string]interface{})["alarmMethod"].(float64))
	alarm.AlarmDescription = data.(map[string]interface{})["alarmDescription"].(string)
	alarm.AlarmType = int(data.(map[string]interface{})["alarmType"].(float64))
	alarm.AlarmTypeParam = data.(map[string]interface{})["alarmTypeParam"].(string)
	alarm.Longitude = data.(map[string]interface{})["longitude"].(float64)
	alarm.Latitude = data.(map[string]interface{})["latitude"].(float64)
	// 保存报警
	if err := e.Orm.Save(&alarm).Error; err != nil {
		e.Error(500, err, "报警保存失败")
		return
	}
}
